package com.shandiangou.crm.util;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

/**
 * Created by jacky on 15/11/26.
 *  Vo对象表单验证工具类
 */
public class VoValidatorUtil {

    private static ValidatorFactory factory = Validation.buildDefaultValidatorFactory();

    private static Validator validator = factory.getValidator();

    /**
     * 校验vo
     * @param vo
     * @return
     */
    public static  String validateVo(Object vo){
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(vo);
        String returnStr = "";
        for(ConstraintViolation<Object> constraintViolation : constraintViolations) {

            returnStr += constraintViolation.getMessage() + ",";
        }
        if(!"".equals(returnStr)){
            return returnStr;
        }
        return null;
    }

    /**
     * 校验单个属性
     * @param vo
     * @param siglePath
     * @return
     */
    public static  String validateVo(Object vo,String siglePath){
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(vo);
        for(ConstraintViolation<Object> constraintViolation : constraintViolations) {
            if(siglePath.equals(constraintViolation.getPropertyPath().toString())){
                return constraintViolation.getMessage();
            }
        }
        return null;
    }
}
